﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System.Text;
using System.Text.RegularExpressions;
using System.Web.Security;

namespace DNA.Mvc
{
    public class PasswordChangedEventObserver:TemplatedMailEventObserver<PasswordChangedEvent>
    {
        private readonly Regex UsernameRegex = new Regex("\\{username\\}", RegexOptions.Compiled);
        private readonly Regex PasswordRegex = new Regex("\\{password\\}", RegexOptions.Compiled);

        private string subject = "User password changed";

        /// <summary>
        /// Get/Sets the email subject
        /// </summary>
        public override string Subject
        {
            get { return subject; }
            set { subject = value; }
        }

        protected override string GetDestinationAddress(PasswordChangedEvent e)
        {
            if (!string.IsNullOrEmpty(e.UserName))
            {
                var user = Membership.GetUser(e.UserName);
                if (user!=null)
                return user.Email;
            }
            return "";
        }

        protected override void OnFormatHtmlBody(PasswordChangedEvent e, ref string html)
        {
            html = UsernameRegex.Replace(html, e.UserName);
            html = PasswordRegex.Replace(html, e.Password);
        }

        protected override void OnFormatTextBody(PasswordChangedEvent e, ref string text)
        {
            var bodyText = new StringBuilder();
            bodyText.Append("Username:")
                .AppendLine(e.UserName)
                .Append("Password:")
                .AppendLine(e.Password);
            text = bodyText.ToString();
        }
    }
}
